package com.yy.xshell.core;

import com.jcraft.jsch.*;
import com.yy.xshell.SshMsgDtO;
import com.yy.xshell.auth.SessionContext;
import com.yy.xshell.auth.UserSessionInfo;
import com.yy.xshell.exceptions.AuthFailException;
import com.yy.xshell.exceptions.SshException;
import com.yy.xshell.loopPull.LoopCore;
import com.yy.xshell.loopPull.SessionStream;
import com.yy.xshell.process.HandlerPipeline;
import com.yy.xshell.process.commandhandler.EndWithHandler;
import com.yy.xshell.process.commandhandler.SignalQuantityHandler;
import com.yy.xshell.process.commandhandler.SpecialSymbolHandler;
import com.yy.xshell.process.resultHandler.*;
import com.yy.xshell.vo.ShellVO;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wxy
 * @version 1.0
 * @date 2024/8/5 17:08
 */
public class SshCore {

    private SshCore(){

    }

    public static final HandlerPipeline<String> COMMAND_HANDLER_PIPELINE = new HandlerPipeline();

    public static final HandlerPipeline<ShellContext> RESULT_HANDLER_PIPELINE = new HandlerPipeline();

    public static final LoopCore loopCore = new LoopCore();

    static {
        COMMAND_HANDLER_PIPELINE.addLast(new SpecialSymbolHandler());
        COMMAND_HANDLER_PIPELINE.addLast(new SignalQuantityHandler());
        COMMAND_HANDLER_PIPELINE.addLast(new EndWithHandler());


        RESULT_HANDLER_PIPELINE.addLast(new DefaultHandler());
        RESULT_HANDLER_PIPELINE.addLast(new RingTheBellHandler());
        RESULT_HANDLER_PIPELINE.addLast(new ClearHandler());
        RESULT_HANDLER_PIPELINE.addLast(new RemoveEmpty());
        RESULT_HANDLER_PIPELINE.addLast(new HistoryHandler());
        RESULT_HANDLER_PIPELINE.addLast(new InsertStrHandler());
        RESULT_HANDLER_PIPELINE.addLast(new StyleHandler());

        loopCore.start();
    }

    public static SshCore instanceOf(){
        return new SshCore();
    }

    private Logger log = LoggerFactory.getLogger(SshCore.class);

    private static Map<String, Map<String , ShellVO>> data = new HashMap<String, Map<String, ShellVO>>();
    private static Map<String, ShellContext.Environment> environments = new HashMap<>();

    public String open(UserSessionInfo userSessionInfo) throws SshException {
        Session session = null;
        InputStream inputStream = null;
        try {
            session = new JSch().getSession(userSessionInfo.getUserName(), userSessionInfo.getHost(), userSessionInfo.getPort());
            session.setPassword(userSessionInfo.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(5000);
            ChannelShell shell = (ChannelShell)session.openChannel("shell");
            putSession(session, userSessionInfo.getSessionKey(), userSessionInfo.getUserId(), shell, userSessionInfo);
            SessionContext.set(userSessionInfo);
//            shell.setAgentForwarding(true);
//            shell.setPty(true);
//            shell.setPtyType("vt100");
//            shell.setXForwarding(true);
            StringBuffer hello = new StringBuffer();
            shell.setInputStream(null);
            log.warn("ssh打开");
            inputStream = shell.getInputStream();
            shell.connect();
            byte[] b = new byte[1024];
            int i = 0;
            while (i <= 3){
                while (inputStream.available() > 0) {
                    int read = inputStream.read(b);
                    String a = new String(b, 0, read);
                    System.out.println(a);
                    hello.append(a);
                }
                i++;
                TimeUnit.MILLISECONDS.sleep(100);
            }
            inputStream.close();
            return hello.toString();
        }catch (Exception e){
            log.info("SshCore==open", e);
            if(e instanceof JSchException){
                throw new AuthFailException(e.getMessage());
            }
            log.error("ssh,打开异常", e);
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inputStream = null;
            }
        }
        return null;
    }

    private void putSession(Session session, String sessionKey, String userId, ChannelShell channelShell, UserSessionInfo sessionInfo){
        Map<String, ShellVO> shellVOMap = new HashMap<String, ShellVO>();
        shellVOMap.put(sessionKey, new ShellVO(session, null, channelShell, sessionInfo));
        data.put(userId, shellVOMap);
    }

    public static UserSessionInfo getUserSessionInfo(String userId, String sessionKey){
        UserSessionInfo userSessionInfo = data.get(userId).get(sessionKey).getUserSessionInfo();
        SessionContext.set(userSessionInfo);
        return SessionContext.get();
    }


    public static void main(String[] args) {
        SshCore sshCore = SshCore.instanceOf();
        //"111","we", "root", "@Ahcj@2022", "123.60.65.155", 22
        UserSessionInfo sessionInfo = new UserSessionInfo();
        String text = sshCore.open( sessionInfo);
        //;log.debug("sshMsg:{}", text);
    }

    public boolean sendCommand(String userId, String sessionKey , String command, Channel channel) {
        if(StringUtils.isEmpty(command) || sessionKey == null){
            return false;
        }
        Map<String, ShellVO> userData = data.get(userId);
        if(userData == null){
            return false;
        }
        ShellVO shellVO = userData.get(sessionKey);
        command += " \n";
        InputStream inputStream = null;
        try {
            ChannelExec shell = (ChannelExec)shellVO.getSession().openChannel("exec");
            shell.setCommand(command);
            shell.setErrStream(System.err);
            shell.setInputStream(null);
            shell.setPty(true);
            log.warn("ssh打开");
            inputStream = shell.getInputStream();
            shell.connect();
            shellVO.setChannelExec(shell);
            shellVO.setExecClose(Boolean.FALSE);
            data.get(userId).put(sessionKey, shellVO);
            byte[] b = new byte[1024];
            int readLen = 0, i = 0;
            while (true) {
                while (inputStream.available() > 0) {
                    readLen = inputStream.read(b);
                    channel.writeAndFlush(new TextWebSocketFrame(new String(b, 0, readLen)));
                }
                ++i;
                if(data.get(userId).get(sessionKey).isExecClose()){
                    break;
                }
                TimeUnit.MILLISECONDS.sleep(100);
            }
            inputStream.close();
            shell.connect();
        }catch (Exception e){
            log.error("发生命令异常", e);
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }

    public void commentClose(String userId, String sessionKey) {
        ShellVO shellVO = data.get(userId).get(sessionKey);
        shellVO.setExecClose(Boolean.TRUE);
    }

    public void setEnvironment(SshMsgDtO sshMsgDtO){
        if(sshMsgDtO.getEnvironment() != null){
            environments.put(sshMsgDtO.getUserId(), sshMsgDtO.getEnvironment());
        }
    }

    /**
     * 关闭该用户所有通道
     * @param userId 用户id
     */
    public void closeByUserId(String userId) {
        Map<String, ShellVO> map = data.get(userId);
        if(map != null){
            for(String key : map.keySet()){
                ShellVO vo = map.get(key);
                if(vo.getChannelExec() != null){
                    vo.getChannelExec().disconnect();
                }
                if(vo.getChannelShell() != null){
                    vo.getChannelShell().disconnect();
                }
                vo.getSession().disconnect();
                map.remove(key);
            }
            data.remove(userId);
        }
        List<SessionStream> remove = loopCore.getAndRemoveByUserId(userId);
        if(remove != null && remove.size() != 0){
            remove.forEach(item->{
                try {
                    item.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        log.info("用户全部{}资源关闭成功", userId);
    }

    public void sendShell(String userId, String sessionKey, String command, Channel channel) {
        ShellVO shellVO = data.get(userId).get(sessionKey);
        ChannelShell shell = shellVO.getChannelShell();
        if(!shell.isConnected()){
            try {
                shell.connect();
            } catch (JSchException e) {
                e.printStackTrace();
            }
        }
        try {
            OutputStream outputStream = shell.getOutputStream();
            outputStream.write(COMMAND_HANDLER_PIPELINE.handler(command).getBytes());
            outputStream.flush();
//            outputStream.close();
            InputStream stream = shell.getInputStream();
            SessionStream sessionStream = new SessionStream();
            sessionStream.setChannel(channel);
            sessionStream.setUserId(userId);
            sessionStream.setSessionKey(sessionKey);
            sessionStream.setInputStream(stream);
            sessionStream.setSessionInfo(SessionContext.get());
            sessionStream.setEnvironment(environments.get(userId));
            loopCore.add(sessionStream);
        }catch (Exception e){
            log.error("发送shell命令出错", e);
        }
    }

    public static void putSessionInsertStr(UserSessionInfo sessionInfo, String s) {
        ShellVO shellVO = data.get(sessionInfo.getUserId()).get(sessionInfo.getSessionKey());
        shellVO.setInsertStr(s.substring(0, s.length()-5));
        sessionInfo.setInsertStr(s);
    }

    public static String getInsertStr(String userId,String sessionKey){
        return data.get(userId).get(sessionKey).getInsertStr();
    }

    public static void setBeforStr(String userId,String sessionKey, String str){
        data.get(userId).get(sessionKey).setBeforStr(str);
    }

    public static String getBeforStr(String userId,String sessionKey){
        return data.get(userId).get(sessionKey).getBeforStr();
    }
}
